﻿/*******************************************************
Copyright © 2008-2009 Active Technologies Group, Inc. (ATGi)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*******************************************************/
using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace ATGi.CS.Components
{
    public interface IFFMpegProcessWrapper
    {
        void Execute();
        string FFMpegPath { get; set; }
        string InputVideoPath { get; set; }
        string OutputImagePath { get; set; }
        int ProcessTimeout { get; set; }
        int StartTimeOffset { get; set; }
    }

    class FFMpegProcessWrapper : IFFMpegProcessWrapper
    {
        public string FFMpegPath { get; set; }
        public string InputVideoPath { get; set; }
        public string OutputImagePath { get; set; }
        
        public int StartTimeOffset { get; set; }
        public int ProcessTimeout { get; set; }

        public void Execute()
        {
            // Create the ffmpeg.exe command line.
            StringBuilder argsBuilder = new StringBuilder();

            argsBuilder.AppendFormat(" -i \"{0}\"", InputVideoPath);     // Input file name
            argsBuilder.AppendFormat(" -ss {0}", StartTimeOffset);      // Start time offset (seconds)
            argsBuilder.Append(" -vframes 1");                          // Set the number of video frames to export
            argsBuilder.Append(" -f image2");                           // Force format
            argsBuilder.AppendFormat(" -y \"{0}\"", OutputImagePath);   // Output file name (overwrite output file)

            // Create a process to generate the preview image.
            using (Process ffmpegProcess = new Process())
            {
                ffmpegProcess.StartInfo.FileName = FFMpegPath;
                ffmpegProcess.StartInfo.Arguments = argsBuilder.ToString();
                ffmpegProcess.StartInfo.UseShellExecute = false;
                ffmpegProcess.StartInfo.RedirectStandardOutput = true;
                ffmpegProcess.StartInfo.RedirectStandardError = true;

                // Execute the process.
                ffmpegProcess.Start();

                // If the process exited successfully...
                if (!ffmpegProcess.WaitForExit(ProcessTimeout * 1000) || 
                    ffmpegProcess.ExitCode != 0)
                {
                    StringWriter sw = new StringWriter();

                    // Kill the process if necessary.
                    if (ffmpegProcess.HasExited == false)
                    {
                        ffmpegProcess.Kill();
                        sw.WriteLine("FFmpeg process was forcibly killed after the following output:");
                    }
                    else
                        sw.WriteLine("FFmpeg process exited after the following output:");

                    // Log the process output/error streams.                        
                    sw.WriteLine();
                    sw.WriteLine(ffmpegProcess.StandardError.ReadToEnd());

                    throw new Exception(sw.ToString());
                }
            }
        }
    }
}
